<?php
/**
 * (actions)
 */
namespace App\Admin\Actions\Reimburse;

use App\Models\Reimburse\ReimburseDetail;
use App\Models\Reimburse\ReimbursePaid;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
class BatchAudit extends BatchAction
{
    public $name = '审核';

    public function handle(Collection $collection)
    {
        try{
            $count = 0;
            foreach ($collection as $model) {
                if($model->audit_status != 1){
                    continue;
                }
                foreach($model->paid as $item){
                    if($item->apply_status == 2 && $item->audit_status == 1){
                        $item->audit_status = 2;
                        $item->save();
                    }else{
                        continue;
                    }
                }
                if($model->paid_type == 2){
                    $paidStatus = $this->_auditForPaid($model->reimburse_no);
                    if(!is_null($paidStatus)){
                        $model->paid_status = $paidStatus;
                    }
                }
                $model->audit_status = 2;
                $flag = $model->save();
                if($flag){
                    $count++;
                }
            }
            return $this->response()->success("成功通过{$count}条记录！")->refresh();
        }catch (\Exception $e){
            report($e);
            return $this->response()->error('系统异常！');
        }
    }

    private function _auditForPaid($reimburseNo){
        $rp = ReimbursePaid::query()
            ->where('reimburse_no',$reimburseNo)
            ->where('apply_status',2)
            ->where('audit_status',2)
            ->where('paid_status',1)
            ->where('paid_amount',0)
            ->first();
        if($rp){
            $date = date('Y-m-d H:i:s');
            $rp->paid_status = 2;
            $rp->paid_date = $date;
            $rp->save();
            $paidStatus = ReimbursePaid::query()->where('reimburse_no',$rp->reimburse_no)->pluck('paid_status')->toArray();
            $status = ReimbursePaid::extractStatus($paidStatus);
            $rd = ReimburseDetail::query()->where('reimburse_no',$rp->reimburse_no)->first();
            $rd->paid_status = $status;
            $rd->paid_date = $date;
            $rd->report_date = date('Y-m-01',strtotime($date));
            $rd->{'paid_amount_'.$rp->order_by} = 0;
            $rd->save();
        }
        return $status ?? null;
    }
}
